﻿using RJi.FanucInterface3.Common;
using RJi.FanucInterface3.Common.Enum;
using RJi.FanucInterface3.Models;
using System.Diagnostics;
using System.Threading.Tasks;

namespace ConsoleApp1;

internal class Program
{
    private static Stopwatch _stopwatch = new Stopwatch();

    private static async Task Main(string[] args)
    {
        Console.Write("IP:");
        var ip = Console.ReadLine();

        var builder = FanucRbtBuilderFactory.CreateBuilder();

        var robot = builder
                    .SetHost(ip, "robot1")
                    .WithTimeout(300)
                    .WithPrimaryTable(
                        config =>
                        {
                            config
                                .RegisterAlarmHistory(10)
                                .RegisterSysVar("$MCR.$GENOVERRIDE", SysVarType.Int)
                                .RegisterSysVar("$SCR_GRP[1].$ROBOT_ID", SysVarType.String)
                                .RegisterAxisTorques()
                                .RegisterTask();
                        })
                    .WithIO(config =>
                    {
                        config.RegisterInput(InputType.Di, 1, 20)
                              .RegisterInput(InputType.Ui)
                              .RegisterBatteryAlarm();
                             
                    })
                    .Build();
        var start = Stopwatch.GetTimestamp();
        await Task.Run(() => robot.Connect());
        var elapsed = Stopwatch.GetElapsedTime(start);
        Console.WriteLine(elapsed.ToString());
        while (true)
        {
            robot.RefreshPrimaryTable();
            robot.RefreshInput();
            robot.RefreshOutput();
            Console.WriteLine($"table1：{robot.RefreshPrimaryTableTime}ms");

            var task = robot.Reader.PrimaryTableVariables["TASK"];
            var alarms = robot.Reader.PrimaryTableVariables["ALARM_LIST"];
            var speed = robot.Reader.PrimaryTableVariables["$MCR.$GENOVERRIDE"];
            var id = robot.Reader.PrimaryTableVariables["$SCR_GRP[1].$ROBOT_ID"];
            var torques = robot.Reader.PrimaryTableVariables["CUR_TORQUE"];
            var isBatteryAlarm = robot.Reader.GetBatteryAlarm();

            //Console.WriteLine(task.ToString());
            //Console.WriteLine(speed.ToString());
            //Console.WriteLine(id.ToString());
            //Console.WriteLine(isBatteryAlarm.ToString());

            //foreach (var alarm in (RbtAlarm[])alarms)
            //{
            //    Console.WriteLine(alarm.ToString());
            //}

            //foreach (var torque in (RbtSysVar[])torques)
            //{
            //    Console.WriteLine(torque.ToString());
            //}

            Thread.Sleep(10000);
        }

        Console.ReadKey();
    }
}